package com.hj.dapp.business.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.hj.dapp.business.oss.model.FileUpLoadDto;
import com.hj.dapp.business.oss.model.FileUploadVo;
import com.hj.dapp.business.oss.service.OssService;
import com.hj.dapp.common.constant.OssConstant;
import com.hj.dapp.common.util.Base64Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author 胡奥程
 * @version 1.0
 * @date 2024/1/2
 */
@Slf4j
@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private OSS ossClient;

    @Override
    public FileUploadVo fileUpload(FileUpLoadDto fileUpLoadDto) {
        try {
            InputStream inputStream = null;
                    // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
            String objectName = "";
            String fileName = UUID.randomUUID().toString().substring(0, 10) + "." + fileUpLoadDto.getExtName();
            if (OssConstant.TYPE_ID_CARD.equals(fileUpLoadDto.getType())) {
                inputStream = Base64Util.base64ToStream(fileUpLoadDto.getData());
                objectName = OssConstant.TYPE_ID_CARD + "/" + fileName;
            } else if (OssConstant.TYPE_CONTACT.equals(fileUpLoadDto.getType())) {
                inputStream = fileUpLoadDto.getInputStream();
                objectName = OssConstant.TYPE_CONTACT + "/" + fileName;
            } else if (OssConstant.TYPE_AVATAR.equals(fileUpLoadDto.getType())) {
                inputStream = fileUpLoadDto.getInputStream();
                objectName = OssConstant.TYPE_AVATAR + "/" + fileName;
            }

            // 创建OSSClient实例。
            PutObjectRequest putObjectRequest = new PutObjectRequest(OssConstant.BUCKET_NAME, objectName, inputStream);
            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            FileUploadVo fileUploadVO = new FileUploadVo();
            fileUploadVO.setName(fileName);
            fileUploadVO.setPath(OssConstant.FILE_PATH+"/"+objectName);
            return fileUploadVO;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
